<script setup lang="tsx">
import { computed, reactive, ref, watch } from 'vue';
import { NButton } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import type { XxlJobGroup, XxlJobGroupEditAndCreateParams } from '@/service/api';
import { createXxlJobGroup, updateXxlJobGroup } from '@/service/api';
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict';

defineOptions({
  name: 'XxlJobGroupOperateModel'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: XxlJobGroup | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.base.xxl.executor.addExecutor'),
    edit: $t('page.base.xxl.executor.editExecutor')
  };
  return titles[props.operateType];
});

type Model = XxlJobGroupEditAndCreateParams;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: 0,
    appname: '',
    title: '',
    addressType: 0,
    addressList: ''
  };
}

type RuleKey = Extract<keyof Model, 'appname' | 'title' | 'addressType'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  appname: defaultRequiredRule,
  title: defaultRequiredRule,
  addressType: defaultRequiredRule
};

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});

function handleAddressTypeChange(value: string | number | boolean) {
  if (value === 0) {
    model.addressList = '';
  }
}

/** 提交 */
async function handleSubmit() {
  await validate();

  submitLoading.value = true;

  if (props.operateType === 'edit') {
    const { error } = await updateXxlJobGroup(model.id as number, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createXxlJobGroup(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-200">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="auto">
        <NFormItem :label="$t('page.base.xxl.executor.appname')" path="appname">
          <NInput v-model:value="model.appname" :placeholder="$t('page.base.xxl.executor.form.appname')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.xxl.executor.executorTitle')" path="title">
          <NInput v-model:value="model.title" :placeholder="$t('page.base.xxl.executor.form.executorTitle')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.xxl.executor.addressType')" path="addressType">
          <NRadioGroup v-model:value="model.addressType" @update:value="handleAddressTypeChange">
            <NRadio
              v-for="item in getIntDictOptions(DICT_TYPE.EXECUTOR_REGISTER_TYPE)"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </NRadioGroup>
        </NFormItem>
        <NFormItem :label="$t('page.base.xxl.executor.addressList')" path="addressList">
          <NInput
            v-model:value="model.addressList"
            type="textarea"
            :disabled="model.addressType === 0"
            :placeholder="$t('page.base.xxl.executor.form.addressList')"
          />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
